import { VuexModule, Module, Action, Mutation, getModule } from 'vuex-module-decorators'
import UserState from './interface'
import store from '@/store'
import { login, getUserInfo, modifyProfile } from '@/apis/user'
import { getToken, setToken, removeToken } from '@/utils/cookies'
import { message } from 'ant-design-vue'

@Module({ dynamic: true, store: store, name: 'user', namespaced: true })
class User extends VuexModule implements UserState {
  public token = getToken() || ''
  public username = ''
  public profileLink = ''
  public isAdmin = 0
  public email = ''

  get GET_TOKEN() {
    return this.token;
  }

  get GET_USERNAME() {
    return this.username;
  }

  get GET_PROFILE() {
    return this.profileLink;
  }

  get GET_IS_ADMIN() {
    return this.isAdmin;
  }

  get GET_EMAIL() {
    return this.email;
  }

  @Mutation
  private SET_TOKEN(token: string) {
    this.token = token
  }

  @Mutation
  private SET_USERNAME(username: string) {
    this.username = username
  }

  @Mutation
  private SET_PROFILE(profileLink: string) {
    this.profileLink = profileLink
  }

  @Mutation
  private SET_IS_ADMIN(isAdmin: number) {
    this.isAdmin = isAdmin
  }

  @Mutation
  private SET_EMAIL(email: string) {
    this.email = email
  }

  @Action({ rawError: true })
  public async Login(userInfo: { id: string, password: string }) {
    let { id, password } = userInfo;
    id = id.trim();
    password = password.trim();
    const { data, msg } = await login(id, password);
    message.success(msg);
    setToken(data.token);
    this.SET_TOKEN(data.token);
  }

  @Action({ rawError: true })
  public ResetToken() {
    removeToken()
    this.SET_TOKEN('')
  }

  @Action({ rawError: true })
  public async GetUserInfo() {
    if (this.token === '') {
      throw Error('GetUserInfo: token is undefined!')
    }

    const { data } = await getUserInfo()
    if (!data) {
      throw Error('Verification failed, please Login again.')
    }

    const { username, profileLink, isAdmin, email } = data
    this.SET_USERNAME(username)
    this.SET_PROFILE(profileLink)
    this.SET_IS_ADMIN(isAdmin)
    this.SET_EMAIL(email)
  }

  @Action
  public async LogOut() {
    if (this.token === '') {
      throw Error('退出登录: token 不存在!')
    }
    removeToken()
    this.SET_TOKEN('')
    this.SET_USERNAME('')
    this.SET_PROFILE('')
    this.SET_EMAIL('')
    this.SET_IS_ADMIN(0)
  }

  @Action
  public async ModifyProfile(formData: FormData) {
    const { data } = await modifyProfile(formData);
    this.SET_PROFILE(data.profileLink);
  }
}

export const UserModule = getModule(User)

